<template>
	<div class="ai-question" :class="screenHeight <= 720 ? 'minScreen' : ''" id="ai-question" :style="showDetail ? 'width:30%' : ''">
		<el-card class="box-card" v-if="showQuesition">
			<div slot="header" class="clearfix-ai-question" style="display: flex; justify-content: space-between">
				<span class="title">{{ title }}</span>
				<span class="close" @click="close">x</span>
			</div>
			<div class="contents">
				<el-form :model="form" :rules="form.rules" ref="ruleForm">
					<el-table class="question-table" :data="form.tableData" :span-method="arraySpanMethod" @row-click="clickRow" stripe border style="width: 100%">
						<el-table-column :index="indexMethod" type="index" align="center" width="40"> </el-table-column>
						<el-table-column prop="name" label="意图点" align="center" width="180"> </el-table-column>
						<el-table-column prop="reply" :show-overflow-tooltip="true" label="AI坐席回复话术" align="center" width="330">
							<template slot-scope="scope">
								<el-form-item :prop="'tableData.' + scope.$index + '.reply'" :rules="form.rules.reply">
									<p v-if="scope.row.isSet">
										<el-input
											v-model="scope.row.reply"
											:disabled="showDetail"
											placeholder="请输入AI回复话术"
											@blur="validateReply"
											@input="e => (scope.row.reply = validForbid(e))"
											:id="'replyId' + scope.$index"
											@keyup.native="prevent($event)"
											onkeydown="if (event.keyCode===13){return false;}"
										></el-input>
									</p>
									<p class="edit-class" :class="scope.row.reply.trim() !== '' ? '' : 'empty'" v-else @click="chageTalks(scope.row, scope.$index)"
										>{{ scope.row.reply.trim() !== '' ? scope.row.reply : '请输入AI回复话术' }}
									</p>
								</el-form-item>
							</template>
						</el-table-column>
						<el-table-column align="center" v-if="!showDetail">
							<template slot="header" slot-scope="scope">
								<span class="add" @click="addAttr(scope)">+ 添加变量</span>
							</template>
						</el-table-column>
					</el-table>
				</el-form>
			</div>
			<div class="tips">
				<p v-show="isShowTips">*仅支持输入长度100以内的中文字符，不支持特殊符号输入</p>
			</div>
			<div class="page-seize">
				<PageSize :pages="pages" @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage" :pageSizes="[5, 10]" />
			</div>
			<div class="btn" v-if="!showDetail">
				<el-button class="reset-btn" @click="reset">全部清空</el-button>
				<el-button class="save-btn" @click="save">保存</el-button>
			</div>
		</el-card>
		<UserAttribute v-if="showAttr" :dialogVisible="showAttr" @on-ok="surekey" @on-cancel="closeAttr" />
	</div>
</template>

<script>
import PageSize from '@/views/components/PageSize.vue';
import { validateAiTalk } from '@/utils/formValidate';
import UserAttribute from '../../../AiWorkFlow/AiTemplateView/UserAttribute.vue';
import { mapState } from 'vuex';
import { insertStr } from '@/utils/tool';
export default {
	components: {
		PageSize,
		UserAttribute
	},
	props: {
		title: {
			type: String,
			default: () => '智能问答'
		},
		tips: {
			type: String,
			default: () => '仅支持输入长度100以内的中文字符，不支持特殊符号输入'
		},
		showQuesition: {
			type: Boolean,
			defualt: () => false
		},
		pages: {
			type: Object,
			default: () => {}
		},
		showDetail: {
			type: Boolean,
			default: () => false,
			required: true
		},
		screenHeight: {
			type: Number,
			default: () => 1080,
			required: true
		}
	},
	data() {
		return {
			showAttr: false,
			currentTalks: null,
			isShowTips: false,
			form: {
				tableData: [],
				rules: {
					reply: [{ validator: validateAiTalk, trigger: ['blur'] }]
				}
			},
			editBusinessId: this.$route.params.id,
			currentIndex: 0
		};
	},
	mounted() {},
	watch: {
		tableData: {
			handler(value) {
				console.log(value, 'intelligentReply.tableData');
				this.form.tableData = JSON.parse(JSON.stringify(value));
			},
			deep: true
		}
	},
	computed: {
		...mapState({
			tableData: state => state.intelligentReply.replies
		})
	},

	methods: {
		reset() {
			this.$confirm('您确定全部清空 AI 坐席回复话术吗?', '温馨提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				left: true
			})
				.then(() => {
					this.form.tableData.map(item => {
						item.reply = '';
					});
					this.save();
					this.$refs['ruleForm'].resetFields();
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消清除'
					});
				});
		},
		validateReply() {
			this.$refs['ruleForm'].validate(valid => {
				if (!valid) {
					this.isShowTips = true;
				} else {
					this.isShowTips = false;
				}
			});
		},
		save() {
			this.$refs['ruleForm'].validate(valid => {
				if (valid) {
					this.form.tableData.map(item => {
						item.isSet = false;
					});
					this.isShowTips = false;
					// console.log(this.form.tableData, 'tableData:');
					let data = this.form.tableData.map(item => {
						return {
							name: item.name,
							reply: item.reply
							// variables: item.variables ? item.variables.filter(k => item.reply.includes(`{{${k.name}}}`)) : []
						};
					});
					console.warn('saveData', data);
					this.$emit('save', data);
				} else {
					this.form.tableData.map(item => {
						item.isSet = true;
					});
					this.isShowTips = true;
					return false;
				}
			});
		},
		close() {
			this.$refs['ruleForm'].resetFields();
			this.$emit('closeQuesiton');
		},
		arraySpanMethod({ columnIndex }) {
			if (columnIndex === 2) {
				return [1, 2];
			}
		},
		clickRow(row) {
			this.currentTalks = row;
			// console.log('clickRow:', row);
		},
		chageTalks(row, index) {
			row.isSet = !row.isSet;
			this.currentIndex = index;
			// console.warn('chageTalks:', this.currentIndex, 'row:', row);
		},
		addAttr() {
			this.showAttr = true;
		},
		surekey(data, businessData) {
			console.log(businessData, 'surekey', data);
			if (this.currentTalks) {
				// 鼠标光标在哪就要在哪添加变量
				const wordsDom = document.getElementById('replyId' + this.currentIndex);
				// console.warn('wordsDom:', wordsDom, this.currentIndex);
				if (wordsDom) {
					if (data) {
						this.currentTalks.reply = insertStr(this.currentTalks.reply, wordsDom, `{{客户信息_${data.bizscenario_role.name}_${data.name}_${data.id}}}`);
					}
					if (businessData) {
						if (wordsDom) {
							this.currentTalks.reply = insertStr(this.currentTalks.reply, wordsDom, `{{业务信息_${businessData.name}_${businessData.id}}}`);
						}
					}
				}
				console.log(this.currentTalks.reply, 'reply:', this.form.tableData);
			}
			this.showAttr = false;
		},
		closeAttr() {
			this.showAttr = false;
		},

		// 数据分页
		changePageSize(val) {
			this.$emit('changePageSize', val);
		},
		changeCurrentPage(val) {
			this.$emit('changeCurrentPage', val);
		},
		// 恢复初值
		restore() {
			this.form.tableData = JSON.parse(JSON.stringify(this.tableData));
		}
	}
};
</script>

<style lang="less" scoped>
.minScreen {
	transform: scale(0.7);
	left: 0 !important;
	top: 0 !important;
}
.ai-question {
	position: absolute;
	top: 100px;
	left: 100px;
	.clearfix-ai-question {
		display: flex;
		justify-content: space-between;
		.close {
			color: #c9c9ce;
			font-size: 16px;
			cursor: pointer;
		}
		.title {
			font-size: 14px;
			font-weight: 700;
			color: #333333;
		}
	}
	.el-input {
		height: 100%;
	}
	.el-form-item {
		width: 100%;
		margin: 0;
		p {
			width: 100%;
		}
	}
	.edit-class {
		line-height: 30px;
		height: 30px;
		text-align: center;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	.tips {
		font-size: 12px;
		color: #f56c6c;
		padding: 10px 0;
	}
	.btn {
		text-align: right;
		padding: 12px 0;
	}
	.empty {
		color: #babbbc;
	}
	.reset-btn {
		color: #999;
	}
	.save-btn {
		color: #fff;
		background-color: #6384fe;
	}
	.page-seize {
		padding: 10px 0;
	}
	.add {
		cursor: pointer;
		color: #6384fe;
	}
}
</style>
<style lang="less">
.ai-question {
	.el-table_1_column_3 {
		border-right: 0;
		text-align: center;
	}
	.el-dialog {
		z-index: 3000;
	}
	.has-gutter tr th {
		background: #f8f8f9;
	}
	tr td {
		background-color: #fff;
		height: 30px;
		cursor: pointer;
		padding: 0;
	}
	.el-table--striped .el-table__body tr.el-table__row--striped td {
		background-color: #fff;
	}
	.el-table--enable-row-hover .el-table__body tr:hover > td {
		background-color: #eff7fc;
	}
	.cell {
		width: 100% !important;
		padding: 0 !important;
	}
	.el-form-item__content {
		line-height: 30px;
	}
	.contents input {
		height: 30px;
		width: 100%;
		padding: 0;
		border: 1px solid #fff;
		text-align: center;
	}
	.question-table {
		.el-table_15_column_50 {
			border-right: 0;
		}
	}
}
.ai-question .el-tooltip__popper {
	max-width: 24%;
}
.ai-question .el-tooltip__popper,
.ai-question .el-tooltip__popper.is-dark {
	left: 60% !important;
	background: #f6f6f6 !important;
	color: #4e5254 !important;
	box-shadow: 0px 2px 3px 0px rgba(0, 0, 0, 0.06);
	border-radius: 4px;
	text-align: center;
}
.ai-question .el-tooltip__popper .popper__arrow,
.ai-question .el-tooltip__popper .popper__arrow::after {
	border: 0;
}
.ai-question .disable {
	pointer-events: none;
	width: 39%;
}
</style>
